package library

import (
	"encoding/json"
	"errors"
	"github.com/PuerkitoBio/goquery"
	"regexp"
	"strings"
)

type NivodM3u8Json struct {
	Url string `json:"url"`
}

func GetNivodM3u8Url(url string) (string, error) {
	dom, err := Get(url)
	if err != nil {
		return "", err
	}
	query, err := goquery.NewDocumentFromReader(strings.NewReader(string(dom)))
	if err != nil {
		return "", err
	}
	playUrl := query.Find(".player-box-main").Find("script").Text()
	//正则匹配是否找到
	findBool, err := regexp.MatchString(`^var\s+player_aaaa=.*$`, playUrl)
	if err != nil {
		return "", err
	}
	if !findBool {
		return "", errors.New("播放链接查询失败")
	}
	replace := regexp.MustCompile(`var\s+player_aaaa=`)
	var playUrlData NivodM3u8Json
	if err := json.Unmarshal([]byte(replace.ReplaceAllString(playUrl, "")), &playUrlData); err != nil {
		return "", err
	}
	return playUrlData.Url, nil
}
